<?php
/**
 * 平台站内消息-消息管理
 * User: xf
 * Date: 2018/8/22
 * Time: 10:01
 */
namespace App\Http\Controllers\Admin\System;
use App\Http\Controllers\Admin\Controller;
use App\Models\News\Notification;
use App\Models\Trader;
use App\Models\User;
use Illuminate\Http\Request;
use Validator,DB;

class MessageController extends Controller {
    /**
     * 消息管理-分页信息
     * POST: /admin/system/message/get-lists
     * @param Request $request
     * @param string keyword 消息管理模糊查询
     * @param int read 0未读\1已读
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     **/
    public function getLists(Request $request)
    {
        $request = $request->only(['keyword','page','limit','read']);
        $page = isset($request['page']) ? $request['page'] : 1;
        $limit = isset($request['limit']) ? $request['limit'] : config('rhzc.pageSize');
        //读取状态[0未读\1已读]
        $read = isset($request['read']) ? $request['read'] : '';
        //类型选择
        $data = new Notification();
        // 系统消息
        $data = $data->where('type','App\Notifications\SystemNotification');
        if ( !empty($read)) {
            if ($read == 1) {
                $data = $data->whereNull('read_at');
            }
            if ($read == 2) {
                $data = $data->whereNotNull('read_at');
            }
        }
        $total = $data->count();
        $data  = $data->select('id', 'type', 'data', 'read_at', 'created_at')
            ->orderBy('created_at', 'desc')
            ->skip(($page - 1) * $limit)
            ->take($limit)
            ->get()
            ->toArray();
        $return = ['total'=>$total,'list'=>$data];
        // 返回分页数据 (总条数, 数据数组)
        return $this->success('查询成功',$return);
    }

    /**
     * 执行消息单发操作
     * 访问地址: POST: /admin/system/message/singleDo
     * @param Request $request
     * @param string name  接收人昵称
     * @param string title  消息标题
     * @param string content  发送内容
     * @return mixed
     **/
    public function singleDo(Request $request)
    {
        $params = $request->only(['type','name','title','content']);
        //数据验证
        $validator = Validator::make($params, [
            'name'   => 'required',
            'title'   => 'required',
            'content' => 'required'
        ], [
            'name.required' => '接收人不能为空',
            'title.required'   => '消息标题不能为空',
            'content.required' => '消息内容不能为空'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $type = isset($params['type']) ? $params['type'] : 1;
        // 用户
        if ($type == 1) {
            $user = User::where(function ($q) use ($params) {
                $q->orWhere('users.mobile', $params['name'])
                    ->orWhere('users.nickname', $params['name']);
            })
                ->first();
            if ( !$user ) {
                return $this->error('未找到用户，请重新输入接收人');
            }
            //发送消息
            $user_res = sendSystemNoticeForUser(User::find($user->id), $params['title'], $params['content']);
            if ($user_res != null) {
                return $this->error('用户消息发送失败，请重新操作！');
            }
        }else{
            $user = Trader::where(function ($q) use ($params) {
                $q->orWhere('trader.mobile', $params['name'])
                    ->orWhere('trader.username', $params['name']);
            })
                ->first();
            if ( !$user ) {
                return $this->error('未找到用户，请重新输入接收人');
            }
            //发送消息
            $user_res = sendSystemNoticeForTrader(Trader::find($user->id), $params['title'], $params['content']);
            if ($user_res != null) {
                return $this->error('用户消息发送失败，请重新操作！');
            }
        }

        return $this->success('操作成功');
    }

    /**
     * 执行消息群发操作
     * 访问地址: POST: admin/system/message/groupDo
     * @param Request $request
     * @param int type 1用户 2供应商 3全部
     * @param string title  消息标题
     * @param string content  发送内容
     * @return mixed
     **/
    public function groupDo(Request $request)
    {
        $params = $request->only(['type','title','content']);
        //数据验证
        $validator = Validator::make($params, [
            'title'   => 'required',
            'content' => 'required'
        ], [
            'title.required'   => '消息标题不能为空',
            'content.required' => '消息内容不能为空'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $type = isset($params['type']) ? $params['type'] : 3;
        switch ($type) {
            case 1: // 用户
                $user_res = sendSystemNoticeForAllUser($params['title'], $params['content']);
                if ($user_res != null) {
                    return $this->error('用户消息发送失败，请重新操作！');
                }
                break;
            case 2: // 供应商
                $trader_res = sendSystemNoticeForAllTrader($params['title'], $params['content']);
                if ($trader_res != null) {
                    return $this->error('供应商消息发送失败，请重新操作！');
                }
                break;
            default:
                // 全部用户
                $user_res = sendSystemNoticeForAllUser($params['title'], $params['content']);
                if ($user_res != null) {
                    return $this->error('用户消息发送失败，请重新操作！');
                }

                // 全部用户
                $trader_res = sendSystemNoticeForAllTrader($params['title'], $params['content']);
                if ($trader_res != null) {
                    return $this->error('供应商消息发送失败，请重新操作！');
                }
                break;
        }

        return $this->success('操作成功');
    }

    /**
     * 删除数据(单条或多条)
     * POST:/admin/system/message/delete
     * @param Request $request
     * @param string ids id数组 [2,3,4,...]
     * @return mixed
     */
    public function delete(Request $request)
    {
        $request = $request->only(['ids']);
        // 获取id集合
        $ids = isset($request['ids']) ? $request['ids'] : [];
        // 判断是否有值
        if ( !count($ids)) {
            return $this->error( '缺失参数');
        }
        $res = Notification::whereIn('id', $ids)->delete();
        if ( !$res) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 标注已查看(单条或多条)
     * POST:admin/system/message/see
     * @param Request $request
     * @param string ids id数组 [2,3,4,...]
     * @return mixed
     */
    public function see(Request $request)
    {
        $date    = date('Y-m-d H:i:s', time());
        $params = $request->only(['ids']);
        // 获取id集合
        $ids = isset($params['ids']) ? $params['ids'] : [];
        // 判断是否有值
        if ( !count($ids)) {
            return $this->error( '缺失参数');
        }
        $res = Notification::whereIn('id', $ids)->update([
            'read_at'    => $date,
            'updated_at' => $date
        ]);
        if ( !$res) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 获取平台未读消息数量
     * GET:admin/system/message/emailCount
     * @param Request $request
     * @return mixed
     */
    public function emailCount(Request $request)
    {
        $count = Notification::where('notifiable_type', 'App\Models\Admin\AdminUser')
            ->whereNull('read_at')
            ->count();
        return $this->success('查询成功', $count);
    }
}